﻿using DemoForBillOcr;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Windows.Forms;
using TaxAssistantBase;
using WindowsFormsApp2;
namespace BillHelper
{
    public partial class CompGroup : Form
    {
        //0.声明自适应类实例  
        AutoAdaptWindowsSize autoAdaptSize;
        private string currentDeclareDate;
        AdminJM adminJm = new AdminJM();
        public CompGroup()
        {
            InitializeComponent();
        }
        private Process process = new Process();
        private Panel[] pl;
        private TextBox[] tb;
        private Label[] lab;
        List<BatchInfo> allbif = new List<BatchInfo>();
        private int currentPageIndex = 0;
        private int pageSize = 15;
        private string currentCompanyName;
        private bool isnStartPross = false;
        private static string currentTime = DateTime.Now.ToString("yyyyMMdd");
        private static string currentBatchIdTime = DateTime.Now.ToString("yyyyMMddHHmmss");
        private List<InvoiiceOcrModel> currentPiaoJuInfo;
        private List<InvoiiceOcrModel> bpmlist;

        private List<HighSpeedRailTicket> hsrtList = new List<HighSpeedRailTicket>();
        WsdLogger chulilog = new WsdLogger("ChuLiLog");
        public void compGroupCR(string currentDeclareDate, string currentCompanyName)
        {
            this.currentDeclareDate = currentDeclareDate;
            currentSearchComp.Select();
            LoadDataAndShowPanel();
        }
        private void CompGroup_Load(object sender, EventArgs e)
        {
            //  FormBorderStyle = FormBorderStyle.None;
            //管道用的
            Control.CheckForIllegalCrossThreadCalls = false;
            allbif = new List<BatchInfo>();
            pl = new Panel[] { tag1, tag2, tag3, tag4, tag5, tag6, tag7, tag8, tag9, tag10, tag11, tag12, tag13, tag14, tag15 };
            tb = new TextBox[] { comp1, comp2, comp3, comp4, comp5, comp6, comp7, comp8, comp9, comp10, comp11, comp12, comp13, comp14, comp15 };
            lab = new Label[] { num1, num2, num3, num4, num5, num6, num7, num8, num9, num10, num11, num12, num13, num14, num15 };
            getDeclare();//获取征期
                         //getPiaoJuAllClick();
            
            LoadDataAndShowPanel();//绑定公司
            currentSearchComp.Select();
            shuangXiangHuanCKJ();//双重缓存
            getPiaoJuTime.Enabled = true;
            #region 窗体缩放
            autoAdaptSize = new AutoAdaptWindowsSize(this);
            autoAdaptSize.InitControlsInfo(this.Controls[0]);
            #endregion
        }
        private void shuangXiangHuanCKJ()
        {
            panel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance
       | System.Reflection.BindingFlags.NonPublic).SetValue(panel1, true, null);
        }
        private void getPiaoJuAllClick()
        {
            bpmlist = new List<InvoiiceOcrModel>();
            InvoiiceOcrModel bm = new InvoiiceOcrModel();
            HighSpeedRailTicket hsrt = new HighSpeedRailTicket();
            string tpresult = "";
            string apiurl2 = ApiUrlList.GETDATAALL;
            string apiurlGT = ApiUrlList.GETHSRTINFO;
            string result = "";
            try
            {
                bm.declaredate = currentDeclareDate;
                bm.companyTaxnum = currentCompanyName;
             
                result = RestDataTool.Post2(out tpresult, bm, apiurl2, out bpmlist);
                if (bpmlist.Count>0) {
                    if (!string.IsNullOrEmpty(bpmlist[0].batchnumber)) {
                        hsrt.invoiceId = int.Parse(bpmlist[0].batchnumber);
                        result = RestDataTool.PostGT(out tpresult, hsrt, apiurlGT, out hsrtList);
                    }
                }
                

            }
            catch (Exception es)
            {
                WsdLogger.yxlog("error", "获取票据数据：" + es.Message);
                return;
            }
            if (bpmlist.Count > 0)
            {
                currentPiaoJuInfo = new List<InvoiiceOcrModel>();
                currentPiaoJuInfo = bpmlist;
            }
            else
            {
                currentPiaoJuInfo = new List<InvoiiceOcrModel>();
            }
        }
        private List<InvoiiceOcrModel> chuliPiaoJu(string declaredate)
        {
            List<InvoiiceOcrModel> bplist = new List<InvoiiceOcrModel>();
            if (bpmlist.Count > 0)
            {
                foreach (InvoiiceOcrModel bp in bpmlist)
                {
                    if (declaredate == bp.declaredate)
                    {
                        bplist.Add(bp);
                    }
                }
            }
            return bplist;
        }
        //获取公司分类
        private List<BatchInfo> getCompGroups()
        {
            string apiurl2 = ApiUrlList.GETCOMPAYDATA;
            string temp = "";
            List<BatchInfo> bif = new List<BatchInfo>();
            BatchInfo bpmtemp = new BatchInfo();
            bpmtemp.companyName = "";
            bpmtemp.batchtimes =  currentDeclareDate;
            bpmtemp.addtime = DateTime.Today.ToString("yyyy-MM-dd");//临时测试先注释
            string mac = "";
            try
            {
                mac = getMac();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "获取mac地址报错" + ex.Message);
            }
            bpmtemp.companyTaxnum = mac;
            try
            {
                var result = RestDataTool.Post(out temp, bpmtemp, apiurl2, out bif);
                int shu = 0;
                foreach (BatchInfo bin in bif) {
                    shu += Convert.ToInt32(bin.processingnum);
                }
                return bif;
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "获取公司分组报错" + ex.Message);
            }
            return bif;
        }
        //获取MAC地址
        private string getHostIpName()
        {
            string mac = "";
            ManagementClass mc;
            mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    mac = mo["MacAddress"].ToString();
            }
            return mac;
        }
        //获取公司分组
        public void getCompany(string declatedate, string companyOCrname)
        {
            currentDeclareDate = declatedate;
            object sender = new object();
            EventArgs e = new EventArgs();
            ShowPanel();
        }
        private void LoadDataAndShowPanel()
        {
            LoadDataAndShowPanel(true);
        }
        private void ShowPanel()
        {
            LoadDataAndShowPanel(false);
        }
        private void LoadDataAndShowPanel(bool isLoadData)
        {
            if (isLoadData)
            {
                allbif = getCompGroups();
            }
            List<BatchInfo> biflist = null;
            if (allbif != null && allbif.Count > 0)
            {
                var text = Convert.ToString(currentSearchComp.Text).Trim();//去空格得值
                if (!string.IsNullOrEmpty(text))
                {
                    var list = from currentdata in allbif where currentdata.companyName.Contains(currentSearchComp.Text) select currentdata;
                    biflist = list.ToList();
                }
                else
                {
                    biflist = allbif.ToList();
                }
            }
            ShowPanel(biflist);
        }
        //添加到界面上
        private void ShowPanel(List<BatchInfo> bif)
        {
            if (bif == null)
                bif = new List<BatchInfo>();
            numcom.Text = bif == null ? "0" : bif.Count.ToString();
            int bifCount = bif == null ? 0 : bif.Count;
            rightbtn.Enabled = currentPageIndex > 0;
            int pageTotal = (bif.Count / pageSize) + ((bif.Count % pageSize) > 0 ? 1 : 0);
            leftbtn.Enabled = (pageTotal - 1 > currentPageIndex);
            int beginIndex = currentPageIndex * pageSize;
            int endIndex = (currentPageIndex + 1) * pageSize - 1;
            if (bif.Count <= endIndex)
            {
                endIndex = bif.Count - 1;
            }
            int total = endIndex - beginIndex;
            for (int i = 0; i < pl.Length; i++)
            {
                if (i > total)
                {
                    tb[i].Text = "";
                    lab[i].Text = "";
                    lab[i].Tag = "";
                    pl[i].Visible = false;
                }
                else
                {
                    //this.panel1.Controls.Add(pl[i]);
                    pl[i].Visible = true;
                    tb[i].Text = bif[beginIndex + i].companyName;
                    lab[i].Text = bif[beginIndex + i].processingnum;
                    lab[i].Tag = bif[beginIndex + i].batchnumber;
                }
            }
        }
        private void getDeclare()
        {
            string temp;
            string apiurl = ApiUrlList.DECLARYDATE;//获取征期
            string date;
            string delaredate;
            var result = RestOrcTool.Post(out temp, new InvoiiceOcrModel(), apiurl);
            date = Convert.ToString(result);
            delaredate = date.Split(':')[1].Replace("\"", "");
            currentDeclareDate = delaredate;
        }
        private void leftbtn_Click(object sender, EventArgs e)
        {
            currentPageIndex++;
            ShowPanel();
        }
        private void rightbtn_Click(object sender, EventArgs e)
        {
            currentPageIndex--;
            ShowPanel();
        }
        private void button1_MouseMove(object sender, MouseEventArgs e)
        {
            Search.BackgroundImage = Properties.Resources.headGroupdianSearch;
        }
        private void Search_MouseLeave(object sender, EventArgs e)
        {
            Search.BackgroundImage = Properties.Resources.headGroupSearch;
        }
        private void Search_Click(object sender, EventArgs e)
        {
            LoadDataAndShowPanel();
        }
        //管道通信
        public void StartClient()
        {
            WsdLogger errorlog = new WsdLogger("errorLog");
            try
            {
                NamedPipeServerStreamTool tool = new BillHelper.NamedPipeServerStreamTool(ShowMessage);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "管道错误：" + ex.Message);
            }
        }
        public void ShowMessage(string message)
        {
            if (!string.IsNullOrEmpty(message))
            {
                string[] messages = message.Split(new string[] { "$$" }, StringSplitOptions.None);
                if (messages[0] == "0")
                {
                    //进行文本框展示
                    string messagesinfo = messages[1];
                    saoMiaoShow(messagesinfo);
                }
                if (messages[0] == "1")
                {
                    string batchid = messages[1];
                    string compName = messages[2];
                    int imgNum = int.Parse(messages[3]);
                    int ocrImgNum = int.Parse(messages[4]);
                    //进行数据进度展示
                    piaoJuZhanShi(batchid, compName, imgNum, ocrImgNum);
                }
            }
        }
        private void saoMiaoShow(string messagesinfo)
        {
            if (messagesinfo == "扫描仪已启动,请背面朝上横向放入票据!")
            {
                try
                {
                    string message = messagesinfo.Split(',')[0] + "\r\n" + messagesinfo.Split(',')[1];
                    SaoMiaoYiShow.Text = message;
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "分割报错：" + ex.Message);
                    SaoMiaoYiShow.Text = messagesinfo;
                }
            }
            else
            {
                SaoMiaoYiShow.Text = messagesinfo;
            }
        }
        private void piaoJuZhanShi(string batchid, string compName, int imgNum, int ocrImgNum)
        {
            if (imgNum == ocrImgNum)
            {
                for (int i = 0; i < allbif.Count; i++)
                {
                    if (batchid == allbif[i].batchnumber)
                    {
                        allbif.Remove(allbif[i]);
                    }
                }
                List<BatchInfo> tempCompGroup = getCompGroups();
                IDictionary<string, BatchInfo> dicstr = new Dictionary<string, BatchInfo>();
                try
                {
                    for (int k = 0; k < allbif.Count; k++)
                    {
                        if (!dicstr.ContainsKey(allbif[k].companyName))
                        {
                            dicstr.Add(allbif[k].companyName, allbif[k]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "添加错误：" + ex.Message);
                }
                foreach (BatchInfo bif in tempCompGroup)
                {
                    if (!dicstr.ContainsKey(bif.companyName))
                    {
                        allbif.Add(bif);
                    }
                }
                ShowPanel();
            }
            else
            {
                //1.1如果不存在则，增加
                AddCompGroupsAndBindCompany(batchid, compName, ocrImgNum, imgNum);
            }
        }
        public void AddCompGroupsAndBindCompany(string batchuid, string companyName, int ocrImgnum, int imgNum)
        {
            bool dd = false;
            for (int i = 0; i < pl.Length; i++)
            {
                //1.要找控件是否存在
                //1.2如果存在，则直接更新界面数据
                if (Convert.ToString(lab[i].Tag) == batchuid)
                {
                    dd = true;
                    tb[i].Text = companyName;
                    lab[i].Text = ocrImgnum + "/" + imgNum;
                    allbif[i].processingnum = ocrImgnum + "/" + imgNum;
                    break;
                }
            }
            if (!dd)
            {
                allbif.Insert(0, new BatchInfo()
                {
                    batchnumber = batchuid,
                    companyName = companyName,
                    processingnum = ocrImgnum + "/" + imgNum
                });
            }
            ShowPanel();
        }
        public void ShowForm2()
        {
            //主目录：Application.StartupPath + \SaoMiao.exe @"C:\Code\SaoMIaos\BillHelper\bin\Debug\billHelper.exe"
            chulilog.Write("打开扫描程序");
            process.StartInfo.FileName = Path.Combine(Application.StartupPath + @"\SaoMiaoShiB", "SaoMiaoShiB.exe");
            process.StartInfo.Arguments = currentTime;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.Verb = "runas";
            try
            {
                process.Start();
                isnStartPross = true;
            }
            catch (Exception e)
            {
                WsdLogger.yxlog("error", "打开进程异常，错误原因：" + e.Message);
            }
            try
            {
                  StartClient();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "打开扫描程序报错：" + ex.Message);
            }
        }
        public void ShowForm2Test()
        {   
            try
            {
                 StartClient();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "打开扫描程序报错：" + ex.Message);
            }
        }
        private void leftbtn_MouseMove(object sender, MouseEventArgs e)
        {
            leftbtn.BackgroundImage = Properties.Resources.dianleft;
        }
        private void leftbtn_MouseLeave(object sender, EventArgs e)
        {
            leftbtn.BackgroundImage = Properties.Resources.left;
        }
        private void rightbtn_MouseLeave(object sender, EventArgs e)
        {
            rightbtn.BackgroundImage = Properties.Resources.right;
        }
        private void rightbtn_MouseMove(object sender, MouseEventArgs e)
        {
            rightbtn.BackgroundImage = Properties.Resources.dianright;
        }
        //点击图片事件
        private void tag1_Click(object sender, EventArgs e)
        {
            string company = "";
            Panel pls = sender as Panel;
            if (pls != null)
            {
                foreach (TextBox com in tb)
                {
                    if (Convert.ToString(com.Tag) == Convert.ToString(pls.Tag))
                    {
                        company = com.Text;
                    }
                }
            }
            SatrtAdminUi(company);
        }
        //打开展示界面
        private void SatrtAdminUi(string company)
        {
            Hide();
            string addtime = DateTime.Today.ToString("yyyyMMdd");
            adminJm.Show();
            currentCompanyName = company;
            getPiaoJuAllClick();
            adminJm.fuzhiCompanyName(company, addtime, currentPiaoJuInfo, this, isnStartPross, process, hsrtList);
        }
        int yiru = 0;
        int yichu = 0;
        //移出
        private void tag1_MouseLeave(object sender, EventArgs e)
        {
            if (yichu == 0)
            {
                yiru = 0;
                Panel ps = sender as Panel;
                if (ps != null)
                {
                //    ps.BackgroundImage = Properties.Resources.shu;
                    foreach (TextBox tbox in tb)
                    {
                        if (Convert.ToString(ps.Tag) == Convert.ToString(tbox.Tag))
                        {
                          //  tbox.BackColor = ColorTranslator.FromHtml("#3486EA");
                        }
                    }
                }
            }
            yichu++;
        }
        //移入
        private void tag1_MouseMove(object sender, MouseEventArgs e)
        {
            if (yiru == 0)
            {
                yichu = 0;
                Panel ps = sender as Panel;
                if (ps != null)
                {
                   // ps.BackgroundImage = Properties.Resources.dianshu;
                    foreach (TextBox tbox in tb)
                    {
                        if (Convert.ToString(ps.Tag) == Convert.ToString(tbox.Tag))
                        {
                         //   tbox.BackColor = ColorTranslator.FromHtml("#4DA3F0");
                        }
                    }
                }
            }
            yiru++;
        }
        //移出字体
        private void comp1_MouseLeave(object sender, EventArgs e)
        {
        
        }
        //移入字体
        private void comp1_MouseMove(object sender, MouseEventArgs e)
        {
            if (yiru == 0)
            {
                yichu = 0;
                TextBox tebox = sender as TextBox;
                if (tebox != null)
                {
                    foreach (Panel pss in pl)
                    {
                        if (Convert.ToString(tebox.Tag) == Convert.ToString(pss.Tag))
                        {
                            //pss.BackgroundImage = Properties.Resources.dianshu;
                        }
                    }
                }
            }
            yiru++;
        }
        //移出票据字体
        private void label1_MouseLeave(object sender, EventArgs e)
        {
        
        }
        //移入票据字体
        private void label1_MouseMove(object sender, MouseEventArgs e)
        {
        
        }
        private void comp1_Click(object sender, EventArgs e)
        {
            string company = "";
            TextBox pls = sender as TextBox;
            if (pls != null)
            {
                foreach (TextBox com in tb)
                {
                    if (Convert.ToString(com.Tag) == Convert.ToString(pls.Tag))
                    {
                        company = com.Text;
                    }
                }
            }
            SatrtAdminUi(company);
        }
        private void label1_Click(object sender, EventArgs e)
        {
            string company = "";
            Label pls = sender as Label;
            if (pls != null)
            {
                foreach (TextBox com in tb)
                {
                    if (Convert.ToString(com.Tag) == Convert.ToString(pls.Tag))
                    {
                        company = com.Text;
                    }
                }
            }
            SatrtAdminUi(company);
        }
        private string getMac()
        {
            string macaddress = AppDomain.CurrentDomain.BaseDirectory + "mac.txt";
            string readmac = "";
            if (File.Exists(macaddress))
            {
                string[] line = File.ReadAllLines(macaddress);
                if (line.Length > 0)
                {
                    readmac = line[0];
                }
                else
                {
                    readmac = getHostIpName();//获取
                }
            }
            else
            {
                readmac = getHostIpName();//获取
            }
            return readmac;
        }
        private void CloseMoTai_Click(object sender, EventArgs e)
        {
            try
            {
                if (isnStartPross)
                {
                    process.Kill();
                }
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "无进程打开" + ex.Message);
            }
            try
            {
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "关闭报错" + ex.Message);
            }
        }
        public void testMessage(string strCompText)
        {
            ShowMessage(strCompText);
        }
        private void SaoMiaoYiShow_TextChanged(object sender, EventArgs e)
        {
            string text = SaoMiaoYiShow.Text;
            adminJm.textChange(text);
        }
        #region 窗体缩放
        private void CompGroup_SizeChanged(object sender, EventArgs e)
        {
            if (autoAdaptSize != null)
            {
                autoAdaptSize.FormSizeChanged();
            }
        }
        #endregion
        private void getPiaoJuTime_Tick(object sender, EventArgs e)
        {
            //getPiaoJuAllClick();
            getPiaoJuTime.Enabled = false;
        }
        private void mainPanel_Paint(object sender, PaintEventArgs e)
        {
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tag11_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tag12_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tag13_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tag14_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tag15_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}